package com.open.common.exception;

import org.apache.commons.lang3.StringUtils;

/**
 * 异常基类，所有内部异常全部集成该基类 
 */
public abstract class BaseException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	public BaseException() {

	}

	/**
	 * @param cause
	 */
	public BaseException(Throwable cause) {
		super(cause);
	}

	public BaseException(String msg) {
		super(resolveMessage(msg));
		String num = resolveNumber(msg);
		if (StringUtils.isNotEmpty(num)) {
			this.number = Integer.parseInt(num);
		}
	}

	public BaseException(String msg, Throwable cause) {
		super(resolveMessage(msg), cause);
		String num = resolveNumber(msg);
		if (StringUtils.isNotEmpty(num)) {
			this.number = Integer.parseInt(num);
		}
	}

	protected int number;

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	public String getMessage() {
		return BaseExceptionUtils.buildMessage(super.getMessage(), this.getCause());
	}

	public Throwable getRootCause() {
		Throwable rootCause = null;

		for (Throwable cause = this.getCause(); cause != null && cause != rootCause; cause = cause.getCause()) {
			rootCause = cause;
		}

		return rootCause;
	}

	public Throwable getMostSpecificCause() {
		Throwable rootCause = this.getRootCause();
		return (Throwable) (rootCause != null ? rootCause : this);
	}

	public boolean contains(Class<?> exType) {
		if (exType == null) {
			return false;
		} else if (exType.isInstance(this)) {
			return true;
		} else {
			Throwable cause = this.getCause();
			if (cause == this) {
				return false;
			} else if (cause instanceof BaseException) {
				return ((BaseException) cause).contains(exType);
			} else {
				while (cause != null) {
					if (exType.isInstance(cause)) {
						return true;
					}

					if (cause.getCause() == cause) {
						break;
					}

					cause = cause.getCause();
				}

				return false;
			}
		}
	}

	static String resolveMessage(String message) {
		if (StringUtils.isNotEmpty(message)) {
			if (message.indexOf("-") != -1) {
				String[] msgs = message.split("-");
				return msgs[1];
			} else {
				return message;
			}
		}
		return null;
	}

	static String resolveNumber(String message) {
		if (StringUtils.isNotEmpty(message)) {
			if (message.indexOf("-") != -1) {
				String[] msgs = message.split("-");
				return msgs[0];
			} else {
				return null;
			}
		}
		return null;
	}

	static {
		BaseExceptionUtils.class.getName();
	}
}
